﻿using com.nm.interfaces;
using com.nm.library.Factorys;
using george.Web.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;

// ReSharper disable once CheckNamespace
namespace com.nm.Helper
{
    /// <summary>
    /// 和图片相关的操作类
    /// </summary>
    public static class ImageHelper
    {
        /// <summary>
        /// 返回完整的图片地址
        /// </summary>
        /// <param name="page"></param>
        /// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        /// <param name="protocol">协议</param>
        /// <returns></returns>
        public static string GetImageUrl(this Page page, string url, string protocol = "http")
        {
            //if (url.StartsWith("~/"))
            url = page.Request.ResolveClientUrl(url);
            return GetImageUrl(url, protocol);
        }

        /// <summary>
        /// 返回完整的图片地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        /// <param name="protocol">协议</param>
        /// <returns></returns>
        public static string GetImageUrl(this HttpRequest request, string url, string protocol = "http")
        {
            //if (url.StartsWith("~/"))
            url = request.ResolveClientUrl(url);
            return GetImageUrl(url, protocol);
        }

        ///// <summary>
        ///// 返回完整的图片地址
        ///// </summary>
        ///// <param name="httpHandler"></param>
        ///// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        ///// <param name="protocol">协议</param>
        ///// <returns></returns>
        //public static string GetImageUrl(this IHttpHandler httpHandler, string url, string protocol = "http") {
        //          return GetImageUrl(url, protocol);
        //}
        /// <summary>
        ///  返回完整的图片地址
        /// </summary>
        /// <param name="context"></param>
        /// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        /// <param name="protocol">协议</param>
        /// <returns></returns>
        public static string GetImageUrl(this interfaces.ISessionContext context, string url, string protocol = "http")
        {
            //if (url.StartsWith("~/"))
            url = context.Request.ResolveClientUrl(url);
            return GetImageUrl(url, protocol);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="url"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="isCut"></param>
        /// <param name="protocol"></param>
        /// <returns></returns>
        public static string GetImageUrl(this interfaces.ISessionContext context, string url, int width, int height, bool isCut = false, string protocol = "http")
        {
            //if (url.StartsWith("~/"))
            url = context.Request.ResolveClientUrl(url);
            return GetImageUrl(url, width, height, isCut, protocol);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="isCut"></param>
        /// <param name="protocol"></param>
        /// <returns></returns>
        public static string GetImageUrl(string url, int width, int height, bool isCut = false, string protocol = "http")
        {
            if (string.IsNullOrWhiteSpace(url)) return url;
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                return url.Replace("/~/", "/");
            }

            if (HttpContext.Current != null)
            {
                url = HttpContext.Current.Request.ResolveClientUrl(url);
            }
            var r = new UriBuilder()
            {
                Scheme = protocol,
                Host = ConfigurationHelper.Get("image-host", "img.km.com"),
                //Port = 80,
                Path = url
            };
            var style = "";
            if (width > 0)
            {
                style += $"_{width}w";
            }
            if (height > 0)
            {
                style += $"_{height}h";
            }
            if (isCut)
            {
                style += $"_cut";
            }
            if (!string.IsNullOrWhiteSpace(style))
            {
                r.Query = "?" + style;
            }
            var port = ConfigurationHelper.Get("image-host-port", 80);
            if (port != 80)
                r.Port = port;
            return r.ToString();
        }

        /// <summary>
        /// 返回完整的图片地址
        /// </summary>
        /// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        /// <param name="protocol">协议</param>
        /// <returns></returns>
        public static string GetImageUrl(string url, string protocol = "http")
        {
            if (string.IsNullOrWhiteSpace(url)) return url;
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                return url.Replace("/~/", "/");
            }
            if (HttpContext.Current != null)
            {
                url = HttpContext.Current.Request.ResolveClientUrl(url);
            }
            var r = new UriBuilder()
            {
                Scheme = protocol,
                Host = ConfigurationHelper.Get("image-host", "img.km.com"),
                //Port = 80,
                Path = url
            };
            var port = ConfigurationHelper.Get("image-host-port", 80);
            if (port != 80)
                r.Port = port;
            return r.ToString();
        }

        /// <summary>
		/// 返回完整的图片地址
		/// </summary>
		/// <param name="fileName">图片名称
		/// <param name="protocol">协议</param>
		/// <returns>地址</returns>
        public static string GetResolveImageUrl(string fileName, string type = "", string protocol = "http")
        {
            var url = string.Empty;
            //if (string.IsNullOrWhiteSpace(fileName))  fileName="default";
            if (HttpContext.Current != null)
            {
                if (type == "good")
                    url = HttpContext.Current.Request.ResolveClientUrl("/terminal/goods/" + fileName + ".jpg");
                if (type == "shop")
                    url = HttpContext.Current.Request.ResolveClientUrl("/terminal/shops/" + fileName + ".jpg");
            }
            var r = new UriBuilder()
            {
                Scheme = protocol,
                Host = ConfigurationHelper.Get("image-host", "image.km.com"),
                //Port = 80,
                Path = url
            };
            var port = ConfigurationHelper.Get("image-host-port", 80);
            if (port != 80)
                r.Port = port;
            if (!fileExists(r.ToString()))
                r.Path = HttpContext.Current.Request.ResolveClientUrl("/terminal/default.jpg");
            return r.ToString();
        }

        /// <summary>
        /// 远程服务器上文件是否存在
        /// </summary>
        /// <param name="furl"></param>
        /// <returns></returns>
        public static bool fileExists(string furl)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(furl);
                HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();
                if (myRes.ContentLength > 0)
                {
                    myRes.Close();
                    return true;
                }
                else
                {
                    myRes.Close();
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="imgs"></param>
        public static void RemoveImages(IEnumerable<string> imgs)
        {
            var context = HttpContext.Current;
            foreach (var img in imgs)
            {
                var file = "";
                try
                {
                    file = context.Server.MapPath(img);
                }
                catch
                {
                    continue;
                }
                var fileInfo = new FileInfo(file);
                if (!fileInfo.Exists) continue;
                //如果路径中不包含“upfile”则为非法操作
                if (!fileInfo.FullName.ToLower().Contains("/upfile/")) return;
                try
                {
                    fileInfo.Delete();
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Remove Image " + img);
                }
            }
        }

        public static void RemoveImages(IEnumerable<ImageItem> imgs)
        {
            var context = HttpContext.Current;
            foreach (var img in imgs)
            {
                if (string.IsNullOrWhiteSpace(img.BucketName))
                {
                    var file = "";
                    try
                    {
                        file = context.Server.MapPath(img.Url);
                    }
                    catch
                    {
                        continue;
                    }
                    var fileInfo = new FileInfo(file);
                    if (!fileInfo.Exists) continue;
                    //如果路径中不包含“upfile”则为非法操作
                    if (!fileInfo.FullName.ToLower().Contains("/upfile/")) return;
                    try
                    {
                        fileInfo.Delete();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Remove Image " + img);
                    }
                }
                else
                {
                    var factory = FactoryMaker.Get<IOssClient>("OSS-Factory", "AlOss.OssClientFactory,AlOss");
                    factory.RemoveObject(img.BucketName, img.Url);
                }
            }
        }

        public class ImageItem
        {
            public string Url { get; set; }
            public string BucketName { get; set; }

            public ImageItem()
            {
            }
        }
    }
}